<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" :style="{ marginTop: safeTop + 'px' }">
					<!-- 不跳转商城主页 -->
				<!-- <image v-if="userInfo.identity != 2" @click="goToProfile" src="/static/base/index/store.png"
					class="menu-icon" mode="aspectFit" /> -->
			</view>
			<view class="header-title" :style="{ marginTop: safeTop + 'px' }">设计师</view>
			<view class="header-right">
			</view>
		</view>

		<!-- 固定区域：搜索框 + 标签栏 -->
		<view class="fixed-section" :style="{ top: fixedSectionTop + 'px' }">
			<!-- 标签栏 -->
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					<text class="tab-text">{{ tab.name }}</text>
				</view>
			</view>

			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<input v-model="searchKeyword" class="search-input" placeholder="设计师名称" @input="onSearchInput" />
					<image src="/static/base/seach.svg" class="search-icon" mode="aspectFit" />
				</view>
			</view>
		</view>

		<!-- 滚动内容区域 -->
		<scroll-view scroll-y class="content">
			<view :style="{ height: contentTop + 'px' }"></view>
			<view class="tab-content">

				<view v-if="currentTab === 0" class="designer-list">
					<view v-if="filteredDesigners.length>0">
						<view v-for="(designer, index) in filteredDesigners" :key="designer.uid" class="designer-item"
							@click="goToDesignerProfile(designer.uid)">
							<image :src="designer.avatar ? designer.avatar : '/static/images/f.png'"
								class="designer-avatar" mode="aspectFill" />
							<view class="designer-info">
								<view style="display: flex;">
									<text
										class="designer-name">{{ designer.nickname ? designer.nickname : '暂无昵称' }}</text>
									<!-- 修改 Tab 0, 1, 2 中的这一部分 -->
									<view class="designer-tag">
										<image class="designer-icon" src="/static/base/index/write.png"></image>
										{{ designer.identity || '设计师' }}
									</view>

								</view>
								<view class="info-row">
									<text class="fans-count">粉丝数：{{ formatFans(designer.fans_count) }}</text>
									<!-- <text class="designer-tag">{{ designer.identity || '设计师' }}</text> -->
								</view>
								<text class="designer-desc">{{ designer.signature || '暂无简介' }}</text>
							</view>
							<view :class="designer.userFollow ? 'followed-btn' : 'follow-btn'"
								@click.stop="followDesigner(designer)">
								<text v-if="!designer.userFollow">关注</text>
								<image v-else src="/static/base/designer/yes.png" class="followed-icon"></image>
							</view>
						</view>
					</view>
					
					<view v-else-if="!isLogin" class="empty-tips">
						<text style="color: #ff914f;" @click="goToLogin">点击登录</text></navigator> 查看设计师哦~
					</view>

					<view v-else class="empty-tips">暂无设计师哦~</view>
				</view>

				<view v-if="currentTab === 1" class="designer-list">
					<view v-if="filteredDesigners.length>0">
						<view v-for="(designer, index) in filteredDesigners" :key="designer.uid" class="designer-item"
							@click="goToDesignerProfile(designer.uid)">
							<image :src="designer.avatar ? designer.avatar : '/static/images/f.png'"
								class="designer-avatar" mode="aspectFill" />
							<view class="designer-info">
								<view style="display: flex;">
									<text
										class="designer-name">{{ designer.nickname ? designer.nickname : '暂无昵称' }}</text>
									<!-- 修改 Tab 0, 1, 2 中的这一部分 -->
									<view class="designer-tag">
										<image class="designer-icon" src="/static/base/index/write.png"></image>
										{{ designer.identity || '设计师' }}
									</view>
								</view>
								<view class="info-row">
									<text class="fans-count">粉丝数：{{ formatFans(designer.fans_count) }}</text>
									<!-- <text class="designer-tag">{{ designer.identity || '设计师' }}</text> -->
								</view>
								<text class="designer-desc">{{ designer.signature || '暂无简介' }}</text>
							</view>
							<view :class="designer.userFollow ? 'followed-btn' : 'follow-btn'"
								@click.stop="followDesigner(designer)">
								<text v-if="!designer.userFollow">关注</text>
								<image v-else src="/static/base/designer/yes.png" class="followed-icon"></image>
							</view>
						</view>
					</view>
					<view v-else-if="!isLogin" class="empty-tips">
						<text style="color: #ff914f;" @click="goToLogin">点击登录</text></navigator> 查看设计师哦~
					</view>
					<view v-else class="empty-tips">暂无设计师哦~</view>
				</view>

				<view v-if="currentTab === 2" class="designer-list">
					<view v-if="filteredDesigners.length>0">
						<view v-for="(designer, index) in filteredDesigners" :key="designer.uid" class="designer-item"
							@click="goToDesignerProfile(designer.uid)">
							<image :src="designer.avatar ? designer.avatar : '/static/images/f.png'"
								class="designer-avatar" mode="aspectFill" />
							<view class="designer-info">
								<view style="display: flex;">
									<text
										class="designer-name">{{ designer.nickname ? designer.nickname : '暂无昵称' }}</text>
									<!-- 修改 Tab 0, 1, 2 中的这一部分 -->
									<view class="designer-tag">
										<image class="designer-icon" src="/static/base/index/write.png"></image>
										{{ designer.identity || '设计师' }}
									</view>
								</view>

								<view class="info-row">
									<text class="fans-count">粉丝数：{{ formatFans(designer.fans_count) }}</text>

								</view>
								<text class="designer-desc">{{ designer.signature || '暂无简介' }}</text>
							</view>
							<view :class="designer.userFollow ? 'followed-btn' : 'follow-btn'"
								@click.stop="followDesigner(designer)">
								<text v-if="!designer.userFollow">关注</text>
								<image v-else src="/static/base/designer/yes.png" class="followed-icon"></image>
							</view>
						</view>
					</view>
					<view v-else-if="!isLogin" class="empty-tips">
						<text style="color: #ff914f;" @click="goToLogin">点击登录</text></navigator> 查看设计师哦~
					</view>
					<view v-else class="empty-tips">暂无设计师哦~</view>
				</view>
				<view style="height: 121.45rpx;"></view>
			</view>
		</scroll-view>

		<TableBar :current="1" :messagecount="messagecount" />
	</view>
</template>

<script>
	import TableBar from '@/components/base/table-bar/Index.vue'
	import {
		getUnreadMessage
	} from '@/api/base/message.js'
	import {
		getDesignerList,
		getFollowList
	} from '@/api/base/designer.js'
	import {
		followUser,
		cancelFollowUser
	} from '@/api/base/index.js'

	import {
		USER_INFO,
		UID,
		LOGIN_STATUS
	} from '@/config/cache';
	import Cache from '@/utils/cache';
	import {
		getBaseUserInfo
	} from '@/api/base/user-center'; // 注意：新接口无参数
	import {
		mapGetters
	} from 'vuex'

	export default {
		components: {
			TableBar
		},
		data() {
			return {
				messagecount: 0,
				userInfo: {},
				safeTop: 0,
				fixedSectionTop: 0,
				contentTop: 0,
				currentTab: 0,
				searchKeyword: '',
				tabs: [{
						name: '新签设计师'
					},
					{
						name: '热门设计师'
					},
					{
						name: '我的关注'
					}
				],
				newDesigners: [],
				hotDesigners: [],
				followedDesigners: [],
				loading: false
			}
		},
		computed: {
			...mapGetters(['isLogin']),
			currentList() {
				if (this.currentTab === 0) return this.newDesigners
				if (this.currentTab === 1) return this.hotDesigners
				return this.followedDesigners
			},
			filteredDesigners() {
				const keyword = this.searchKeyword.trim().toLowerCase()
				if (!keyword) return this.currentList
				return this.currentList.filter(d =>
					(d.nickname && d.nickname.toLowerCase().includes(keyword)) ||
					(d.signature && d.signature.toLowerCase().includes(keyword))
				)
			}
		},
		onLoad() {
			const {
				barTop
			} = this.$util.getWXStatusHeight()
			this.safeTop = barTop + 2
			this.fixedSectionTop = barTop + 35
			this.contentTop = barTop + 135

			this.switchTab(0)
		},
		onShow() {
			if (this.isLogin) {
				this.loadNewDesigners()
				this.initMessage()
				this.getUserInfo(); // 调用无参接口
			}
		},
		methods: {
			initMessage() {
				getUnreadMessage().then(res => {
					if (res.status === 200) {
						this.messagecount = res.data.like + res.data.comment
					} else(err => {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						})
						console.log('获取数据失败', err);
					})
				}).catch(err => {
					console.log('获取数据失败', err);
				})
			},
			goToLogin() {
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/users/wechat_login/index'
				});
				// #endif

				// #ifdef H5
				uni.navigateTo({
					url: '/pages/users/login/index'
				});
				// #endif
			},
			getUserInfo() {
				// 新接口无需传参
				getBaseUserInfo().then(res => {
					const cacheUserInfo = JSON.parse(Cache.get(USER_INFO));
					if (res.status === 200 && res.data) {
						// 将后端返回字段赋值给 userInfo
						this.userInfo = {
							...this.userInfo,
							...res.data,
							// 可选：显式转换数值字段（虽后端返回数字，但保险起见）
							phoneNumber: res.data.phone,
							follow_count: res.data.follow_count || 0,
							fans_count: res.data.fans_count || 0,
							comment_count: res.data.comment_count || 0,
							work_like_count: res.data.work_like_count || 0,
							share_count: res.data.share_count || 0,
							income: res.data.income || '0.00'
						};
					}
				}).catch(err => {
					console.log('获取用户信息失败', err);
					// 可选：失败时重置或提示
				});
			},
			goToProfile() {
				uni.navigateTo({
					url: '/pages/index/index'
				})
			},
			async switchTab(index) {
				if (this.currentTab === index) return
				this.currentTab = index
				this.searchKeyword = ''

				if (this.isLogin) {
					if (index === 0) {
						await this.loadNewDesigners()
					} else if (index === 1) {
						await this.loadHotDesigners()
					} else if (index === 2) {
						await this.loadFollowedDesigners()
					}
				}
			},
			async loadNewDesigners() {
				this.loading = true
				try {
					const res = await getDesignerList('new')
					this.newDesigners = res.data.list || []
				} catch (e) {
					console.error('加载新签设计师失败', e)
					this.newDesigners = []
				} finally {
					this.loading = false
				}
			},
			async loadHotDesigners() {
				this.loading = true
				try {
					const res = await getDesignerList('hot')
					this.hotDesigners = res.data.list || []
				} catch (e) {
					console.error('加载热门设计师失败', e)
					this.hotDesigners = []
				} finally {
					this.loading = false
				}
			},
			async loadFollowedDesigners() {
				this.loading = true
				const uid = Cache.get(UID);

				try {
					const res = await getFollowList(uid, 2, 1, 50)
					this.followedDesigners = res.data.list || []
				} catch (e) {
					console.error('加载关注列表失败', e)
					this.followedDesigners = []
				} finally {
					this.loading = false
				}
			},
			async followDesigner(designer) {
				const {
					uid,
					userFollow
				} = designer

				if (userFollow) {
					// 取消关注：弹出确认框
					uni.showModal({
						title: '提示',
						content: '确定要取消关注吗？',
						success: async (res) => {
							if (res.confirm) {
								await this.handleCancelFollow(designer)
							}
						}
					})
				} else {
					// 关注
					await this.handleFollow(designer)
				}
			},
			async handleFollow(designer) {
				const {
					uid
				} = designer
				try {
					await followUser(uid)
					designer.userFollow = true
					designer.fans_count = (designer.fans_count || 0) + 1
					this.syncFollowStatusInOtherTabs(uid, true, designer.fans_count)
				} catch (e) {
					console.log(e)
					uni.showToast({
						title: '关注失败',
						icon: 'none'
					})
				}
			},
			async handleCancelFollow(designer) {
				const {
					uid
				} = designer
				try {
					await cancelFollowUser(uid)

					// 从“我的关注”列表中移除
					const index = this.followedDesigners.findIndex(d => d.uid === uid)
					if (index !== -1) {
						this.followedDesigners.splice(index, 1)
					}

					// 更新其他列表中的状态（新签、热门）
					designer.userFollow = false
					designer.fans_count = Math.max(0, (designer.fans_count || 0) - 1)
					this.syncFollowStatusInOtherTabs(uid, false, designer.fans_count)

				} catch (e) {
					uni.showToast({
						title: '取消关注失败',
						icon: 'none'
					})
				}
			},
			// 仅同步新签和热门列表中的关注状态（不包括“我的关注”，因为它已被移除）
			syncFollowStatusInOtherTabs(uid, isFollowed, fansCount) {
				const lists = [this.newDesigners, this.hotDesigners]
				lists.forEach(list => {
					const item = list.find(d => d.uid === uid)
					if (item) {
						item.userFollow = isFollowed
						item.fans_count = fansCount
					}
				})
			},
			onSearchInput() {
				// 可后续加防抖
			},
			goToDesignerProfile(uid) {
				uni.navigateTo({
					url: `/pages/sub_base/designer-profile/index?id=${uid}`
				})
			},
			formatFans(fans) {
				if (!fans) return '0'
				if (fans >= 10000) {
					return (fans / 10000).toFixed(1) + '万'
				}
				if (fans >= 1000) {
					return (fans / 1000).toFixed(1) + 'k'
				}
				return fans.toString()
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #F2F8FC;
	}


	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27.76rpx;
		z-index: 100;
	}

	.header-left {
		width: 80rpx;
		height: 76.34rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-title {
		font-size: 31.23rpx;
		font-weight: 600;
		color: #333333;
	}

	.header-right {
		width: 100rpx;
	}

	.empty-tips {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 100rpx 0;
	}

	.fixed-section {
		position: fixed;
		left: 0;
		right: 0;
		z-index: 99;
		background-color: #F2F8FC;
	}

	.menu-icon {
		width: 45rpx;
		height: 45rpx;
	}

	.search-section {
		padding: 13.88rpx 27.76rpx;
	}

	.search-box {
		height: 62.46rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		padding: 0 27.76rpx;
	}

	.search-icon {
		width: 44rpx;
		height: 44rpx;
	}

	.search-input {
		flex: 1;
		height: 52.05rpx;
		font-size: 27rpx;
		color: #666666;
	}

	.tabs {
		display: flex;
		padding: 0 27.76rpx;
		height: 69.4rpx;
		justify-content: center;
		margin: 13.88rpx auto;
	}

	.tab-item {
		height: 69.4rpx;
		display: flex;
		align-items: center;
		padding: 0 35.82rpx;
		position: relative;
	}

	.tab-item.active .tab-text {
		color: #000;
		font-weight: 600;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 30%;
		width: 40%;
		height: 3.47rpx;
		background-color: #000;
	}

	.tab-text {
		font-size: 27.76rpx;
		color: #999999;
	}

	.content {
		height: calc(100vh - 34.7rpx);
	}

	.designer-list {
		display: flex;
		flex-direction: column;
	}

	.designer-item {
		display: flex;
		padding: 29rpx 29rpx;
		align-items: center;
		position: relative;
	}

	.designer-item::after {
		content: '';
		position: absolute;
		left: 130.125rpx;
		right: 27.76rpx;
		bottom: 0;
		height: 2rpx;
		background-color: #000000;
		transform: scaleY(0.1);
		/* 垂直方向压缩一半，视觉上就是 0.5px */
		transform-origin: bottom;
		/* 从底部缩放，避免位置偏移 */
	}

	.designer-avatar {
		width: 96rpx;
		height: 96rpx;
		border-radius: 50rpx;
		background-color: #f0f0f0;
		margin-right: 26rpx;
	}

	.designer-info {
		flex: 1;
	}

	.designer-icon {
		width: 22rpx;
		height: 22rpx;
		margin-right: 4rpx;
		/* 调整图标和文字之间的间距 */
		/* 如果需要垂直居中，可以加 margin-bottom: -2rpx; */
	}

	.designer-name {
		font-size: 36rpx;
		font-weight: 500;
		color: #333333;
		display: block;
		margin-bottom: 12rpx;
	}

	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 10.41rpx;
	}

	.fans-count {
		font-size: 22.555rpx;
		color: #9f9f9f;
		padding: 2rpx 9rpx;
		margin-right: 13.88rpx;
		background-color: #fff;
		border-radius: 8.675rpx;
	}

	.designer-tag {
		display: flex;
		align-items: center;
		/* 保持原有样式 */
		font-size: 24rpx;
		padding: 0 14rpx 8rpx;
		/* 可根据需要调整 */
		margin-left: 24rpx;
		margin-top: 4rpx;
		border-radius: 30rpx;
		border: 2rpx solid #000;
		height: 44rpx;

		/* 新增：设置背景色和文字颜色，使其更清晰 */
		background-color: #fff;
		/* 或者透明 background-color: transparent; */
		color: #000;
	}

	.designer-desc {
		font-size: 24.29rpx;
		color: #b6b6b6;
		display: block;

		display: -webkit-box;
		/* 必须设置为 -webkit-box */
		-webkit-box-orient: vertical;
		/* 设置子元素排列方式为垂直 */
		-webkit-line-clamp: 1;
		/* 限制显示 1 行 */
		overflow: hidden;
		/* 超出隐藏 */
		text-overflow: ellipsis;
		/* 配合使用，虽然多行时主要靠 -webkit-line-clamp */
	}

	.follow-btn {
		width: 104.1rpx;
		height: 55.52rpx;
		color: #ffffff;
		font-size: 24.29rpx;
		background-color: #000;
		border-radius: 27.76rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.followed-btn {
		/* width: 104.1rpx; */
		width: 55.52rpx;
		height: 55.52rpx;
		color: #000;
		font-size: 31.23rpx;
		/* background-color: #f0f0f0; */
		background-color: white;
		border-radius: 27.76rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.followed-icon {
		width: 30rpx;
		height: 30rpx;
	}
</style>